import React from 'react';
import {DndContext, DragEndEvent, MouseSensor, useSensor, useSensors} from "@dnd-kit/core";
import {SortableContext} from "@dnd-kit/sortable";

type ComponentType = {
  children: JSX.Element | JSX.Element[],
  onDragEnd: (oldIndex: number, newIndex: number) => void,
  items: Array<{ id: string, [key: string]: any }>
}
const SortableContainer: React.FC<ComponentType> = (props: ComponentType) => {
  const {onDragEnd, children, items} = props
  const sensors = useSensors(useSensor(MouseSensor, {
    activationConstraint: {
      distance: 8//移动超过8像素才触发拖拽事件
    }
  }))

  function handleDragEnd(event: DragEndEvent) {
    const {active, over} = event
    if (over === null) return
    if (active.id !== over.id) {
      const oldIndex = items.findIndex(item => item.fe_id === active.id)
      const newIndex = items.findIndex(item => item.fe_id === over.id)
      onDragEnd(oldIndex, newIndex)
    }
  }

  return (
    <DndContext
      sensors={sensors}
      onDragEnd={handleDragEnd}
    >
      <SortableContext items={items}>
        {children}
      </SortableContext>
    </DndContext>
  );
};

export default SortableContainer;
